import React, { useEffect } from 'react';
import { Modal, Form, Input, Radio } from 'antd';
import { useIntl } from 'umi';
import { FORMLAYOUT_2 } from '@/utils/const';

import type { DetailsType } from './BasicInfo';

const FormItem = Form.Item;

interface Props {
  visible: boolean;
  curRecord: DetailsType;
  cancel: () => void;
  loading: boolean;
  onSubmit: (values: SubmitType) => void;
}

export interface SubmitType {
  name: string;
  description: string;
  ownerType: string;
}

const EditBasicInfo: React.FC<Props> = props => {
  const { formatMessage: f } = useIntl();
  const [form] = Form.useForm();
  const { visible, curRecord, cancel, loading, onSubmit } = props;

  useEffect(() => {
    if (form && visible) {
      form.setFieldsValue({
        name: curRecord.name,
        description: curRecord.description,
        isPublic: curRecord.ownerType === 'org',
      });
    }
  }, [visible, curRecord]);

  const onOk = () => {
    form.validateFields().then(values => {
      const params = {
        ...values,
        ownerType: values.isPublic ? 'org' : 'group',
        isPublic: undefined,
      }
      onSubmit(params);
    }).catch(err => {
      console.log(err);
    });
  };

  return (
    <Modal
      title={f({ id: 'dataSet.detail.edit' })}
      visible={visible}
      onCancel={cancel}
      confirmLoading={loading}
      onOk={onOk}
      destroyOnClose
      maskClosable={false}
    >
      <Form form={form} {...FORMLAYOUT_2} preserve={false}>
        <FormItem
          label={f({ id: 'dataSet.detail.name' })}
          name='name'
          rules={[
            { required: true, message: f({ id: 'dataSet.detail.name.placeholder' }) }
          ]}
        >
          <Input placeholder={f({ id: 'dataSet.detail.name.placeholder' })} />
        </FormItem>
        <FormItem
          label={f({ id: 'dataSet.detail.description' })}
          name='description'
          // rules={[
          //   { required: true, message: f({ id: 'dataSet.detail.description.placeholder' }) }
          // ]}
        >
          <Input.TextArea placeholder={f({ id: 'dataSet.detail.description.placeholder' })} />
        </FormItem>
        <FormItem
          label={f({ id: 'dataSet.detail.isPublic' })}
          name='isPublic'
          rules={[
            { required: true, message: f({ id: 'dataSet.detail.isPublic.placeholder' }) }
          ]}
        >
          <Radio.Group>
            <Radio value={false}>{f({ id: 'gloal.no' })}</Radio>
            <Radio value={true}>{f({ id: 'gloal.yes' })}</Radio>
          </Radio.Group>
        </FormItem>
      </Form>
    </Modal>
  )
}

export default EditBasicInfo;